<template>
  <div class="app-login">
    <el-dialog :destroy-on-close="true" append-to-body title="刷卡登录"
               :visible.sync="addUserVisible" width="25%" :show-close="false" :before-close="handleClose">
      <el-form label-width="80px">
        <el-form-item label="刷卡数据" style="width: 300px">
          <el-input disabled type="password" @input="onInputCode" v-model="userCode" placeholder="请刷卡..."></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">登录</el-button>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
module.exports = {
  name: 'LoginDialog',
  props: {
    show: { type: Boolean, default: false }
  },
  watch: {
    show (v) {
      if (v) {
        this.addUserVisible = v;
        window.addEventListener('keydown', this.handleKeyPress);
      }
    }
  },
  data () {
    return {
      addUserVisible: false,
      userCode: '',
      inputTime: null
    }
  },
  methods: {

    /**
     * 监听用户输入的值
     */
    onInputCode () {

    },
    handleClose () {
      this.userCode = '';
      this.addUserVisible = false;
      this.$emit('close');
      window.removeEventListener('keydown', this.handleKeyPress);
    },

    onSubmit () {
      let en = localStorage.getItem('EnableDebug');
      if (en === 'true') {
        this.userCode = '-1';
      }
      Login(this.userCode).then(r => {
        if (r.Status) {
          SetUserInfo(r.Data);
          this.$message({
            type: 'success',
            message: '登录成功!'
          });
          this.$EventBus.$emit('login');
        } else {
          this.$message({
            type: 'warning',
            message: '登录失败!'
          });
        }
        this.handleClose();
      });
    },
    /**
     * 监听键盘的输入
     */
    handleKeyPress (e) {
      clearTimeout(this.inputTime);
      const key = e.key;
      this.userCode += key;
      this.inputTime = setTimeout(() => {
        console.log(this.userCode);
        this.onSubmit();
      }, 1000);
    },
  },
  mounted () {
  },
  destroyed () {
    window.removeEventListener('keydown', this.handleKeyPress);
  }
}
</script>

<style scoped>
.app-login {

}
</style>